#include "todotextedit.h"

#include <QMouseEvent>
#include <QTextCursor>
#include <QTextBlock>
#include <QTextLayout>
#include <QTextStream>

TodoTextEdit::TodoTextEdit(QWidget *parent) :
    QTextEdit(parent)
{
    //this->setReadOnly(true);
}

void TodoTextEdit::mouseDoubleClickEvent(QMouseEvent * e)
{
    QTextEdit::mouseDoubleClickEvent(e);

    QString line = getCurrentLine();
    int pos = line.indexOf("|");
    if( pos > 0 ) {
        int number = line.mid(0, pos-1).trimmed().toInt();
        if( number > 0 ) {
            emit itemDoubleClicked(number);
        }
    }

}

QString TodoTextEdit::getCurrentLine()
{

    QTextCursor cursor = this->textCursor();

    int start = cursor.selectionStart();
    QTextLine textLine = cursor.block().layout()->lineForTextPosition(start);

    //FIXME: Encontrar uma forma melhor de fazer isso
    QTextDocument *doc = this->document();
    QString plainText = doc->toPlainText();

    QTextStream ts(&plainText);
    int lineNumber = textLine.lineNumber();
    for(int i=0; i < lineNumber; i++) ts.readLine();
    QString sLine = ts.readLine();

    return sLine;

}
